<template>
  <div class="app-container">
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"/>
      <span>人脉圈设置</span>
      <!-- 1. 人脉圈基本信息 -->
      <div class="table-container">
        <el-form
          ref="infoRef"
          :model="formData"
          :rules="formRules"
          label-width="100px">
          <el-row type="flex" justify="center">
            <el-col :span="20">
              <el-form-item label="标题" prop="title">
                <el-input v-model="formData.title" placeholder="请输入人脉圈标题" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center">
            <el-col :span="20">
              <el-form-item label="类型" prop="type">
                <el-input v-model="formData.type" placeholder="请输入人脉圈类型" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center">
            <el-col :span="20">
              <el-form-item label="话题" prop="topic">
                <el-input v-model="formData.topic" placeholder="请输入人脉圈话题" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center">
<!--            <el-col :span="4">-->
<!--              <el-form-item label="是否公开">-->
<!--                <el-switch-->
<!--                  v-model="formData.visible"-->
<!--                  active-color="#13ce66">-->
<!--                </el-switch>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
            <el-col :span="16" align="right">
              <el-form-item>
                <el-button type="primary" @click="updateInfo">更新</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"/>
      <span>人脉圈人脉管理</span>
      <el-button
        class="btn-add"
        size="medium"
        type="primary"
        style="float: right;margin-bottom: 15px"
        icon="el-icon-plus"
        @click="showDialog()"
      >
        添加
      </el-button>

      <el-table
        ref="tableList"
        v-loading="listLoading"
        :data="networkUsers"
        style="width: 100%"
      >
        <el-table-column align="center">
          <template slot-scope="scope" v-if="scope.row.isAdmin !== 1">
            <el-row type="flex" justify="start" align="top">
              <el-col :span="5">
                <el-avatar size="medium" :src="scope.row.avatar"></el-avatar>
              </el-col>
              <el-col :span="10">
                <div class="text-nickName" align="start">{{ scope.row.nickName }}</div>
                <div class="text-brief" align="start">{{ scope.row.signature }}</div>
              </el-col>
              <el-col :span="9">
                <el-tooltip class="item" effect="dark" content="名片" placement="bottom">
                  <el-button icon="el-icon-user" @click="showCardDialog(scope.row)" circle></el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="移出" placement="bottom">
                  <el-button icon="el-icon-delete" @click="deleteNetworkUser(scope.row.id)" circle></el-button>
                </el-tooltip>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <!--      <div class="pagination-container">
              <el-pagination
                :style="{width: '100%'}"
                background
                layout="prev, pager, next"
                :page-size="queryInfo.pageSize"
                :current-page.sync="queryInfo.pageNum"
                :total="queryInfo.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>-->
    </el-card>

    <!-- 对话框 -->
    <el-dialog title="名片" :visible.sync="cardDialogVisible" width="700px" @close="cardDialogVisible = false"
               :close-on-press-escap="false" :close-on-click-modal="false">
      <!-- 内容主体 -->
      <div align="center">
        <el-card class="friend-card" align="center" shadow="hover">
          <div class="block">
            <el-avatar :size="80" :src="cardInfo.avatar"></el-avatar>
          </div>
          <div style="padding: 14px;">
            <div class="text-nickName" :style="{marginBottom: '10px'}">{{ cardInfo.nickName }}</div>
            <div class="text-brief-long">{{ cardInfo.signature }}</div>
            <el-tag size="small" type="success" class="card-tag">{{ cardInfo.profession }}</el-tag>
            <el-tag size="small" class="card-tag">{{ cardInfo.gender === 1 ? '男' : '女' }}</el-tag>
            <div class="text-info">职业：{{ cardInfo.profession }}</div>
            <div class="text-info">生日：{{ cardInfo.birthday }}</div>
            <div class="text-info">手机：{{ cardInfo.phone }}</div>
            <div class="text-info">邮箱：{{ cardInfo.email }}</div>
          </div>
        </el-card>
      </div>
    </el-dialog>

    <!-- 新增成员 -->
    <el-dialog title="新增成员" :visible.sync="addDialogVisible" width="50%" @close="addDialogVisible = false"
               :close-on-press-escap="false" :close-on-click-modal="false">
      <!-- 内容主体 -->
      <div align="center">
        <el-card class="friend-card" align="center" :style="{width: '60%'}" shadow="hover">
          <!--          <div align="center">-->
          <!--            <div :style="{width: '100%'}">-->
          <!--              <p :style="{width: '15%', float: 'left'}">昵称：</p>-->
          <!--              <el-input v-model="friendsQueryInfo.nickName" placeholder="请输入" size="small" clearable-->
          <!--                        :style="{width: '58%', float: 'left'}">-->
          <!--              </el-input>-->
          <!--              <el-button icon="el-icon-search" type="primary" size="small" @click="getDataList()"-->
          <!--                         :style="{marginLeft: '1px', float: 'left'}" round>查询-->
          <!--              </el-button>-->
          <!--            </div>-->
          <!--          </div>-->
          <div align="center">
            <el-table
              ref="friendList"
              v-loading="friendsListLoading"
              :data="friends"
              style="width: 100%"
              @selection-change="handleSelectionChange">
              >
              <el-table-column
                type="selection"
                width="55">
              </el-table-column>
              <el-table-column label="选择好友" align="left">
                <template slot-scope="scope">
                  <el-row type="flex" justify="start" align="top">
                    <el-col :span="5">
                      <el-avatar size="medium" :src="scope.row.avatar"></el-avatar>
                    </el-col>
                    <el-col :span="19">
                      <div class="text-nickName" align="start">{{ scope.row.nickName }}</div>
                      <div class="text-brief" align="start">{{ scope.row.signature }}</div>
                    </el-col>
                  </el-row>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!--          <div class="pagination-container" align="center">-->
          <!--            <el-pagination-->
          <!--              :style="{width: '100%'}"-->
          <!--              background-->
          <!--              layout="prev, pager, next"-->
          <!--              :page-size="friendsQueryInfo.pageSize"-->
          <!--              :current-page.sync="friendsQueryInfo.pageNum"-->
          <!--              :total="friendsQueryInfo.total"-->
          <!--              @size-change="handleChooseSizeChange"-->
          <!--              @current-change="handleChooseCurrentChange"-->
          <!--            />-->
          <!--          </div>-->
        </el-card>
        <!-- 弹框：底部操作信息 -->
        <div slot="footer" align="center">
          <el-button type="primary" @click="addNetworkUsers"> 添加</el-button>
          <el-button @click="addDialogVisible = false"> 取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getNetworkInfo,
  editNetworkInfo,
  getUsersOfNetwork,
  deleteNetworkUser,
  getUsersWithinNetwork, insertNetworkUsers
} from "@/api/network";
import {mapGetters} from "vuex";

export default {
  computed: {
    ...mapGetters([
      'name',
      'id',
      'user'
    ])
  },
  data() {
    return {
      networkId: '',
      // 添加修改人脉圈表单
      formData: {
        id: '',
        title: '',
        type: '',
        topic: '',
        visible: ''
      },
      // 用户添加表单验证规则
      formRules: {
        title: [
          {required: true, message: '请输入人脉圈标题', trigger: 'blur'},
          {min: 1, max: 20, message: '标题的长度在1～20个字', trigger: 'blur'}
        ],
        type: [
          {required: true, message: '请输入人脉圈类型', trigger: 'blur'},
          {
            min: 1,
            max: 10,
            message: '类型的长度在1～10个字',
            trigger: 'blur'
          }
        ],
        topic: [
          {required: true, message: '请输入人脉圈话题', trigger: 'blur'},
        ]
      },
      listLoading: false,
      networkUsers: [],
      // queryInfo: {
      //   networkId: this.networkId,
      //   total: 1,
      //   pageNum: 1,
      //   pageSize: 5
      // },
      cardDialogVisible: false,
      cardInfo: {},

      addDialogVisible: false,
      //好友查询条件
      friendsQueryInfo: {
        id: '',
        nickName: '',
        account: '',
        total: 0,
        pageNum: 1,
        pageSize: 5
      },
      friendsListLoading: false,
      multipleSelection: [],
      friends: [],
    }
  },
  created() {
    this.getParams()
    this.getFormData()
    this.getDataList()
  },
  methods: {
    // 获取url参数
    getParams() {
      this.networkId = this.$route.query.networkId;
    },

    // 回显人脉圈基本信息
    getFormData() {
      getNetworkInfo(this.networkId).then(res => {
        this.formData = res.data
        this.formData.visible = res.data.visible === 1
      })
    },
    // 更新人脉圈基本信息
    updateInfo() {
      // 提交请求前，表单预验证
      this.$refs.infoRef.validate(async valid => {
        if (!valid) return
        this.formData.visible = this.formData.visible === true ? 1 : 0
        const params = this.formData
        editNetworkInfo(params).then(res => {
          if (res.retCode === '200') {
            this.$message.success('更新成功！')
            this.getFormData()
          }
        }).catch(res => {
          this.$message.error('更新信息失败！')
          // this.$message.error('更新信息失败！' + res.data.retMsg)
        })
      })
    },

    getDataList() {
      this.listLoading = true
      getUsersOfNetwork(this.networkId).then(response => {
        this.networkUsers = response.data
        // this.queryInfo.total = response.data.total
        this.listLoading = false
      }).catch(() => {
        this.networkUsers = []
        this.listLoading = false
      })
    },

    // 显示名片
    showCardDialog(row) {
      this.cardInfo = row
      this.cardDialogVisible = true
    },

    // 显示添加成员对话框
    showDialog() {
      this.addDialogVisible = true
      this.getFriendsList()
    },

    getFriendsList() {
      getUsersWithinNetwork(this.networkId).then(response => {
        this.friends = response.data
        this.friendsListLoading = false
      })
    },

    async deleteNetworkUser(userId) {
      const confirmResult = await this.$confirm(
        '此操作从本人脉圈中移除此成员, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 点击确定 返回值为：confirm
      // 点击取消 返回值为： cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      let params = {networkId: this.networkId, userId}
      deleteNetworkUser(params).then(res => {
        if (res.retCode === '200') {
          this.$message.success('移出人脉圈成功！')
          this.getDataList()
        }
      })
    },

    handleChooseSizeChange(newSize) {
      this.friendsQueryInfo.pageSize = newSize
      this.getFriendsList()
    },

    handleChooseCurrentChange(newSize) {
      this.friendsQueryInfo.pageNum = newSize
      this.getFriendsList()
    },
    // 获得所选的好友信息
    handleSelectionChange(val) {
      // TODO 下一页后数据丢失
      this.multipleSelection = val
      // console.log(this.multipleSelection.map(item => item.id))
    },
    // 添加人脉圈完成
    addNetworkUsers() {
      let friendIds = this.multipleSelection.map(item => item.id)
      console.log(friendIds)
      // 当前用户id
      let userId = this.user.id
      let networkId = this.networkId
      let params = {networkId, userId, friendIds}
      insertNetworkUsers(params).then(res => {
        if (res.retCode === '200') {
          this.$message.success("人脉圈添加成员成功")
          this.getDataList()
        }
      })
      this.addDialogVisible = false

    }
  },
  watch: {
    '$route': 'getParams'
  }
}
</script>

<style lang="scss" scoped>
</style>
